package com.toolmanrln.security.component;

import com.toolmanrln.common.api.ResponseData;
import com.toolmanrln.common.api.ResultCodeEnum;
import com.toolmanrln.common.util.ResponseUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义返回结果：未登录或登录过期
 * Created by macro on 2018/5/14.
 */
@Component
public class RestfulAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message;
        if (exception instanceof LockedException) {
            message = "账户被锁定，请联系管理员!";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期，请联系管理员!";
        } else if (exception instanceof DisabledException) {
            message = "账户被禁用，请联系管理员!";
        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或者密码输入错误，请重新输入!";
        } else if (exception instanceof AuthenticationServiceException || exception instanceof AccountExpiredException || exception instanceof UsernameNotFoundException) {
            message = exception.getMessage();
        } else {
            message = ResultCodeEnum.UNAUTHORIZED.getValue();
        }
        ResponseUtil.responseToJson(response, ResponseData.failed(ResultCodeEnum.UNAUTHORIZED.getKey(), message));
    }
}
